import React, { useState } from 'react';
import {
  Box,
  TextField,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Avatar,
  Typography,
  Divider,
  Paper,
  Chip
} from '@mui/material';
import { Send as SendIcon, Person as PersonIcon } from '@mui/icons-material';

interface ChatMessage {
  id: string;
  playerId: string;
  playerName: string;
  message: string;
  timestamp: Date;
  isSystem?: boolean;
}

interface GameChatProps {
  messages?: ChatMessage[];
  onSendMessage?: (message: string) => void;
  currentPlayerId?: string;
}

const GameChat: React.FC<GameChatProps> = ({
  messages = [],
  onSendMessage,
  currentPlayerId
}) => {
  const [message, setMessage] = useState('');

  const handleSendMessage = () => {
    if (message.trim() && onSendMessage) {
      onSendMessage(message.trim());
      setMessage('');
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <Paper elevation={2} sx={{ height: 400, display: 'flex', flexDirection: 'column' }}>
      <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider' }}>
        <Typography variant="h6" component="h3">
          游戏聊天
        </Typography>
      </Box>
      
      <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
        {messages.length === 0 ? (
          <Box 
            sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center', 
              height: '100%',
              color: 'text.secondary'
            }}
          >
            <Typography variant="body2">
              暂无聊天消息
            </Typography>
          </Box>
        ) : (
          <List dense>
            {messages.map((msg, index) => (
              <React.Fragment key={msg.id}>
                <ListItem 
                  alignItems="flex-start"
                  sx={{
                    flexDirection: msg.playerId === currentPlayerId ? 'row-reverse' : 'row',
                    px: 1
                  }}
                >
                  <ListItemAvatar>
                    <Avatar 
                      sx={{ 
                        width: 32, 
                        height: 32,
                        bgcolor: msg.isSystem ? 'warning.main' : 'primary.main'
                      }}
                    >
                      {msg.isSystem ? '🎲' : <PersonIcon />}
                    </Avatar>
                  </ListItemAvatar>
                  
                  <Box 
                    sx={{ 
                      maxWidth: '70%',
                      ml: msg.playerId === currentPlayerId ? 0 : 1,
                      mr: msg.playerId === currentPlayerId ? 1 : 0
                    }}
                  >
                    <Box 
                      sx={{ 
                        display: 'flex', 
                        alignItems: 'center', 
                        gap: 1,
                        justifyContent: msg.playerId === currentPlayerId ? 'flex-end' : 'flex-start',
                        mb: 0.5
                      }}
                    >
                      <Typography variant="caption" color="text.secondary">
                        {msg.isSystem ? '系统' : msg.playerName}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {formatTime(msg.timestamp)}
                      </Typography>
                    </Box>
                    
                    <Paper 
                      elevation={0}
                      sx={{
                        p: 1,
                        backgroundColor: msg.isSystem 
                          ? 'warning.light' 
                          : msg.playerId === currentPlayerId 
                            ? 'primary.light' 
                            : 'grey.100',
                        borderRadius: msg.playerId === currentPlayerId 
                          ? '12px 4px 12px 12px' 
                          : '4px 12px 12px 12px'
                      }}
                    >
                      <Typography variant="body2" sx={{ wordBreak: 'break-word' }}>
                        {msg.message}
                      </Typography>
                    </Paper>
                  </Box>
                </ListItem>
                {index < messages.length - 1 && <Divider sx={{ my: 1 }} />}
              </React.Fragment>
            ))}
          </List>
        )}
      </Box>
      
      {onSendMessage && (
        <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <TextField
              fullWidth
              size="small"
              placeholder="输入消息..."
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              multiline
              maxRows={3}
              disabled={!onSendMessage}
            />
            <Button
              variant="contained"
              endIcon={<SendIcon />}
              onClick={handleSendMessage}
              disabled={!message.trim() || !onSendMessage}
              sx={{ minWidth: 80 }}
            >
              发送
            </Button>
          </Box>
        </Box>
      )}
    </Paper>
  );
};

export default GameChat;